package com.huluobo.a2110mvpimdemo;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.huluobo.a2110mvpimdemo.adapter.PagerFragmentAdapter;
import com.huluobo.a2110mvpimdemo.addFriend.AddFriendActivity;
import com.huluobo.a2110mvpimdemo.addGroup.AddGroupActivity;
import com.huluobo.a2110mvpimdemo.contact.ContactFragment;
import com.huluobo.a2110mvpimdemo.contact.MyContactFragment;
import com.huluobo.a2110mvpimdemo.conversation.ConversationFragment;
import com.huluobo.a2110mvpimdemo.conversation.MyConversationFragment;
import com.huluobo.a2110mvpimdemo.mine.MineFragment;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;


import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private BottomNavigationView bottomNavigationView;
    private List<Fragment> fragments;
    private PagerFragmentAdapter fragmentAdapter;

    private TextView title;
    private ImageView add;

    //角标相关
    private View badge;
    private TextView count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.main_vp);
        bottomNavigationView = findViewById(R.id.main_nav);
        title = findViewById(R.id.header_title);
        add = findViewById(R.id.header_add);
        add.setVisibility(View.VISIBLE);

        requestPermissions(new String[]{"android.permission.CAMERA", "android.permission.RECORD_AUDIO"}, 102);

        add.setOnClickListener(v -> {
            //实例化popupMenu 第一个参数上下文,第二个参数,是在哪个view上弹出这个menu
            PopupMenu popupMenu = new PopupMenu(this, add);
            //引入menu的布局
            popupMenu.inflate(R.menu.add_menu);
            //menuItem的点击事件
            popupMenu.setOnMenuItemClickListener(item -> {
                switch (item.getItemId()) {
                    case R.id.addFriend:
                        Intent addFriendIntent = new Intent(this, AddFriendActivity.class);
                        startActivity(addFriendIntent);
                        break;
                    case R.id.addGroup:
                        Intent addGroupIntent = new Intent(this, AddGroupActivity.class);
                        startActivity(addGroupIntent);
                        break;
                    case R.id.scan:
                        toScan();
                        break;
                    case R.id.pay:
                        Toast.makeText(this, "收付款", Toast.LENGTH_SHORT).show();
                        break;
                }
                return true;
            });
            //一定要让menu show出来
            popupMenu.show();
        });

        fragments = new ArrayList<>();
//        fragments.add(new ConversationFragment());
        fragments.add(new MyConversationFragment());
//        fragments.add(new ContactFragment());
        fragments.add(new MyContactFragment());
        fragments.add(new MineFragment());

        fragmentAdapter = new PagerFragmentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(fragmentAdapter);
        //viewpager与底部导航的联动
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //当viewPager选中时
                //与底部导航联动
                //通过底部导航栏获取其中position位置的menuItem
                MenuItem item = bottomNavigationView.getMenu().getItem(position);
                switch (item.getItemId()) {
                    case R.id.tab_conversation:
                        title.setText("微信");
                        add.setVisibility(View.VISIBLE);
                        break;
                    case R.id.tab_contact:
                        title.setText("联系人");
                        add.setVisibility(View.VISIBLE);
                        break;
                    case R.id.tab_mine:
                        title.setText("我的");
                        add.setVisibility(View.GONE);
                        break;
                }
                item.setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //设置底部导航和vp进行联动
        bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
            switch (item.getItemId()) {
                case R.id.tab_conversation:
                    viewPager.setCurrentItem(0);
                    break;
                case R.id.tab_contact:
                    viewPager.setCurrentItem(1);
                    break;
                case R.id.tab_mine:
                    viewPager.setCurrentItem(2);
                    break;
            }
            return true;
        });

        //角标相关
        //1.拿到menuView,也就是底部导航栏中的menu
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
        //2.通过mnu才能拿到第一个itemView,也就是需要标记角标的位置
        BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0);

        //3.通过itemView去添加一个角标的布局
        badge = LayoutInflater.from(this).inflate(R.layout.view_badge, itemView, false);
        itemView.addView(badge);
        count = badge.findViewById(R.id.badge_tv);
        count.setText(String.valueOf(EMClient.getInstance().chatManager().getUnreadMessageCount()));

        //添加一个消息监听器
        EMClient.getInstance().chatManager().addMessageListener(messages -> {
            runOnUiThread(() -> {
                badge.setVisibility(View.VISIBLE);
                count.setText(String.valueOf(EMClient.getInstance().chatManager().getUnreadMessageCount()));
            });
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (EMClient.getInstance().chatManager().getUnreadMessageCount() == 0) {
            badge.setVisibility(View.GONE);
        } else {
            badge.setVisibility(View.VISIBLE);
            count.setText(String.valueOf(EMClient.getInstance().chatManager().getUnreadMessageCount()));
        }
    }

    private void toScan() {
        Intent intent = new Intent(this, CaptureActivity.class);
        startActivityForResult(intent, 101);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            String result = data.getExtras().get(CodeUtils.RESULT_STRING).toString();
            EMClient.getInstance().contactManager().aysncAddContact(result, "", new EMCallBack() {
                @Override
                public void onSuccess() {
                    runOnUiThread(() -> {
                        Toast.makeText(MainActivity.this, "扫一扫发送好友请求成功", Toast.LENGTH_SHORT).show();
                    });
                }

                @Override
                public void onError(int code, String error) {
                    runOnUiThread(() -> {
                        Toast.makeText(MainActivity.this, "扫一扫发送好友请求失败:" + error, Toast.LENGTH_SHORT).show();
                    });
                }
            });
        }
    }
}